package sm2ext

import (
	"encoding/asn1"
	"errors"
	"github.com/tjfoc/gmsm/sm2"
	"reflect"
)

var oidSM2ECC = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301} //sm2ECC (China GM Standards Committee)

type pkcs8_alipay struct {
	Version int
	Algo    struct {
		Algorithm  asn1.ObjectIdentifier
		Algorithm2 asn1.ObjectIdentifier
	}

	PrivateKey []byte
}

func ParsePKCS8UnecryptedPrivateKey_alipay(der []byte) (*sm2.PrivateKey, error) {
	var privKey pkcs8_alipay

	if _, err := asn1.Unmarshal(der, &privKey); err != nil {
		return nil, err
	}
	if !reflect.DeepEqual(privKey.Algo.Algorithm, oidSM2) {
		return nil, errors.New("x509: not sm2 elliptic curve")
	}
	if !reflect.DeepEqual(privKey.Algo.Algorithm2, oidSM2ECC) {
		return nil, errors.New("sm2ECC: not sm2 elliptic curve")
	}
	return ParseSm2PrivateKey_openssl(privKey.PrivateKey)
}

func MakePKCS8UnecryptedPrivateKey_alipay(privKey *sm2.PrivateKey) ([]byte, error) {
	var err error
	privKeyPack := pkcs8_alipay{}
	privKeyPack.Algo.Algorithm = oidSM2
	privKeyPack.Algo.Algorithm2 = oidSM2ECC

	keyData := sm2PrivateKey_openssl{
		Version: 1,
	}
	keyData.PrivateKey = append([]byte(nil), privKey.D.Bytes()...)

	var buff []byte
	buff = append(buff, 04)
	buff = append(buff, privKey.X.Bytes()...)
	buff = append(buff, privKey.Y.Bytes()...)
	keyData.PublicKey.BitLength = len(buff) * 8
	keyData.PublicKey.Bytes = buff

	buff, err = asn1.Marshal(keyData)
	//fmt.Printf("private bit string: %x\n", buff)
	privKeyPack.PrivateKey = buff

	buff, err = asn1.Marshal(privKeyPack)
	//fmt.Printf("private key pkcs8(alipay format): %x\n", buff)
	return buff, err
}
